package com.glodon.paas.document.web.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.consts.StringConst;
import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.document.api.bean.Project;
import com.glodon.paas.document.service.FileService;
import com.glodon.paas.document.service.ProjectService;
import com.glodon.paas.document.service.util.WebService;
import com.glodon.paas.document.web.util.SecurityUtils;
import com.glodon.paas.exception.NotFoundException;
import com.glodon.paas.exception.PrivilegeException;

/**
 * @author xur
 */
@Controller
@RequestMapping("/project")
public class ProjectController {

    public static final Logger LOGGER = LoggerFactory.getLogger(ProjectController.class);
    @Autowired
    private ProjectService     projectService;
    @Autowired
    private FileService        fileService;
    @Autowired
    private WebService webService;

    //TODO 目前传递 file 对象，以后需要修改为 Project对象
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public Object createProject(@RequestBody File object,
                              ModelMap model) {
        User user = SecurityUtils.getCurrentUser();
        Project project = projectService.createProject(user.getId(), user.getEmail(), object.getName(), object.getDescription());
        File rootFolder = fileService.getFile(user.getId(), project.getFolderId(), false);
        rootFolder.setDescription(project.getDescription());
        return rootFolder;
    }
    
    //TODO 目前传递 file 对象，以后需要修改为 Project对象
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    public Object updateProject(@RequestBody File object, ModelMap model) {
        Project project = new Project();
        project.setId(object.getProjectId());
        project.setName(object.getName());
        project.setDescription(object.getDescription());
        project = projectService.updateProject(SecurityUtils.getCurrentUser().getId(), project);
        File rootFolder = fileService.getFile(SecurityUtils.getCurrentUser().getId(), project.getFolderId(), false);
        rootFolder.setDescription(project.getDescription());
        return rootFolder;
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public void getProjects(ModelMap model) {
        Set<String> ids = new HashSet<String>();
        User user = SecurityUtils.getCurrentUser();
        List<com.glodon.paas.account.api.bean.Project> accountProjects = webService.getUser(user.getId()).getProjects();
        for (com.glodon.paas.account.api.bean.Project project : accountProjects) {
            ids.add(project.getId());
        }
        List<Project> projects = new ArrayList<Project>();
        for(String id : ids){
            try{
                projects.add(projectService.getProject(user.getId(), id));
            }catch (PrivilegeException e) {
                LOGGER.warn(e.getMessage(), e);
            }
            catch (NotFoundException e) {
                LOGGER.warn(e.getMessage(),e);
            }
        }
        model.addAttribute(StringConst.ITEMS, projects);
    }
    
    @RequestMapping(value = "/{projectId}", method = RequestMethod.DELETE)
    public void deleteProject(@PathVariable("projectId") String projectId, ModelMap model) {
        if (StringUtils.isNotEmpty(projectId)) {
            List<String> failedItems = new ArrayList<String>();
            boolean result = projectService.deleteProject(SecurityUtils.getCurrentUser().getId(), projectId);
            if (!result) {
                failedItems.add(projectId);
            } else {
                webService.deleteProjectRole(SecurityUtils.getCurrentUser().getId(), null, projectId, null,null);
            }
            
            if (!failedItems.isEmpty()) {
                model.put(StringConst.RESULT, StringConst.FAIL);
                model.put(StringConst.FAILED_ITEMS, failedItems);
            }
            model.put(StringConst.RESULT, StringConst.SUCCESS);
        }
    }
}
